<?php defined('SYSPATH') or die('No direct script access.');

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/12/5 14:36
 * Desc: 景点应用控制器
 */
class Controller_Admin_Ferry extends Stourweb_Controller
{
    private $type_id;

    public function before()
    {
        parent::before();
        $this->type_id = Model_Ferry::$typeid;

        $action = $this->request->action();
        if ($action == 'ferry') {
            $param       = $this->params['action'];
            $right       = array(
                'read' => 'slook',
                'save' => 'smodify',
                'delete' => 'sdelete',
                'update' => 'smodify'
            );
            $user_action = $right[$param];
            if (!empty($user_action)) {
                Common::getUserRight('ferry', $user_action);
            }
        } else if ($action == 'add') {
            Common::getUserRight('ferry', 'sadd');
        } else if ($action == 'edit') {
            Common::getUserRight('ferry', 'smodify');
        } else if ($action == 'price') {
            Common::getUserRight('ferryprice', 'slook');
        } else if ($action == 'ajax_price') {
            $param       = $this->params['action'];
            $right       = array(
                'save' => 'smodify',
                'del' => 'sdelete'
            );
            $user_action = $right[$param] ?: 'slook';
            if (!empty($user_action)) {
                Common::getUserRight('ferryprice', $user_action);
            }
        } else if ($action == 'ajax_save') {
            Common::getUserRight('ferry', 'smodify');
        }

        $this->assign('parentkey', $this->params['parentkey']);
        $this->assign('itemid', $this->params['itemid']);
        $this->assign('weblist', Common::getWebList());
        $this->assign('type_id', $this->type_id);
    }

    // 景点列表
    public function action_ferry()
    {
        $action = $this->params['action'];
        if (empty($action)) {
            //显示线路列表页
            $channel_list = St_Functions::get_ota_channel();
            $this->assign('channel_list', $channel_list);
            $this->assign('kindmenu', Common::getConfig('menu_sub.ferrykind'));//分类设置项
            $this->display('admin/ferry/list');
        } else if ($action == 'read') {
            //读取列表
            $start   = Arr::get($_GET, 'start');
            $limit   = Arr::get($_GET, 'limit');
            $keyword = Arr::get($_GET, 'keyword');
            $kindid  = Arr::get($_GET, 'kindid');
            $attrid  = Arr::get($_GET, 'attrid');
            $ch_id   = Arr::get($_GET, 'channel_id');
            $sort    = json_decode(Arr::get($_GET, 'sort'), true);
            $webid   = isset($_GET['webid']) ? Arr::get($_GET, 'webid') : '-1';

            $ferry_model = DB::select(DB::expr("sline_a.*"))
                ->from(['ferry', 'a']);

            if ($sort[0]['property'] == 'displayorder') {
                $ferry_model->join(['allorderlist', 'b'], 'left')
                    ->on('a.id', '=', DB::expr("sline_b.aid"))
                    ->on(DB::expr('sline_b.typeid'), '=', $this->type_id);
            }

            if ($sort[0]['property'] == 'suit_day') {
                $ferry_model->join(['ferry_ticket_price', 'c'], 'left');
                $ferry_model->on('a.id', '=', DB::expr("sline_c.ferryid"));
            }

            $ferry_model->where('a.id', '>', 0);

            if ($webid != -1) {
                $ferry_model->and_where('a.webid', '=', $webid);
            }
            if ($attrid) {
                $ferry_model->and_where(DB::expr(" and FIND_IN_SET({$attrid},sline_a.attrid) "));
            }
            if ($kindid) {
                $ferry_model->and_where(DB::expr(" and FIND_IN_SET({$kindid},sline_a.kindlist) "));
            }
            if ($ch_id > 1) {
                $ferry_model->and_where(DB::expr(" and FIND_IN_SET({$ch_id},sline_a.supplier_channel_id) "));
            } else {
                $ferry_model->and_where(DB::expr(" and (FIND_IN_SET(1,sline_a.supplier_channel_id) OR sline_a.supplier_channel_id IS NULL) "));
            }
            if ($keyword) {
                if (is_numeric($keyword)) {
                    $product_id = St_Product::product_series_decode($keyword, $this->type_id);
                }
                if (isset($product_id) && $product_id) {
                    $ferry_model->and_where(DB::expr(" and (sline_a.id = '{$product_id}' or sline_a.title LIKE '%{$keyword}%') "));
                } else {
                    $ferry_model->and_where(DB::expr(" and sline_a.title LIKE '%{$keyword}%' "));
                }
            }
            $ferry_model->group_by('a.id');
            $total = $ferry_model->execute()->count();
            if (isset($sort[0])) {
                $sorts = $sort[0];
                if ($sorts['property'] == 'displayorder') {
                    $ferry_model->order_by(DB::expr("sline_b.displayorder {$sorts['direction']}"));
                } elseif ($sorts['property'] == 'suit_day') {
                    $ferry_model->order_by(DB::expr("sline_c.day {$sorts['direction']}"));
                } else {
                    $ferry_model->order_by(DB::expr("sline_a.{$sorts['property']} {$sorts['direction']}"));
                }
            } else {
                $ferry_model->order_by(DB::expr("sline_a.modtime DESC,sline_a.addtime DESC"));
            }
            $ferry_model->offset($start)->limit($limit);
            $list = $ferry_model->execute()->as_array();

            $destinations = DB::select()->from('destinations')->execute()->as_array('id', 'kindname');

            foreach ($list as $k => &$v) {
                if ($v['finaldestid']) {
                    $v['finaldestname'] = $destinations[$v['finaldestid']];
                }
                $v['kindname'] = Model_Destinations::get_kindname_list($v['kindlist']);
                $v['attrname'] = Model_Ferry_Attr::get_attrname_list($v['attrid']);
                $v['series']   = St_Product::product_series($v['id'], $this->type_id);//编号
                $v['url']      = Common::getBaseUrl($v['webid']) . '/ferrys/show_' . $v['aid'] . '.html';
                // 图标
                $icon_list = Model_Icon::getIconName($v['iconlist']);
                $icon_name = '';
                foreach ($icon_list as $icon) {
                    if (!empty($icon))
                        $icon_name .= '<span class="c-999 ml-10">[' . $icon . ']</span>';
                }
                $v['iconname'] = $icon_name;
                // 报价有效期
                $v['suit_day'] = Model_Ferry_Ticket_Price::ferry_expire_day($v['id']);
                // 显示平台
                $v['platform'] = St_Functions::get_platform($v['platform']) ?: '未设';
                // 是否需要审核
                $is_examine = DB::select("id")
                                ->from('ferry_ticket')
                                ->where('ferryid', '=', $v['id'])
                                ->where('status', '=',1)
                                ->execute()
                                ->as_array();
                if($is_examine){
                    $is_examine=1;
                }else{
                    $is_examine=0;
                }
                $v['is_examine'] = $is_examine;
            }

            $result['total']   = $total;
            $result['lists']   = $list;
            $result['success'] = true;

            echo json_encode($result);

        } else if ($action == 'save') {
            //保存字段
        } else if ($action == 'delete') {
            //删除某个记录
            $rawdata = file_get_contents('php://input');
            $data    = json_decode($rawdata);
            $id      = $data->id;

            if (is_numeric($id)) //租车
            {
                $model = ORM::factory('ferry', $id);
                $model->delete_clear();
            } else if (strpos($id, 'suit') !== FALSE) {
                $suitid = substr($id, strpos($id, '_') + 1);
                $suit   = ORM::factory('ferry_ticket', $suitid);
                $suit->delete_clear();
                DB::update('ferry')->set(array('price_date' => 0))->execute();
            }
        } else if ($action == 'update') {

            //更新某个字段
            $id     = Arr::get($_POST, 'id');
            $field  = Arr::get($_POST, 'field');
            $val    = Arr::get($_POST, 'val');
            $kindid = Arr::get($_POST, 'kindid');
            if ($field == 'displayorder')  //如果是排序
            {
                $displayorder = empty($val) ? 9999 : $val;
                if (is_numeric($id)) {
                    //如果是景点
                    if (empty($kindid)) {
                        //全局排序
                        $order     = ORM::factory('allorderlist');
                        $order_mod = $order->where("aid='$id' and typeid={$this->type_id} and webid=0")->find();

                        if ($order_mod->id)  //如果已经存在
                        {
                            $order_mod->displayorder = $displayorder;
                        } else   //如果这个排序不存在
                        {
                            $order_mod->displayorder = $displayorder;
                            $order_mod->aid          = $id;
                            $order_mod->webid        = 0;
                            $order_mod->typeid       = $this->type_id;
                        }
                        $order_mod->save();
                        if ($order_mod->saved()) {
                            echo 'ok';
                        } else
                            echo 'no';
                    } else {
                        //按目的地排序
                        $kindorder     = ORM::factory('kindorderlist');
                        $kindorder_mod = $kindorder->where("aid='$id' and typeid={$this->type_id} and classid=$kindid")->find();
                        if ($kindorder_mod->id) {
                            $kindorder_mod->displayorder = $displayorder;
                        } else {
                            $kindorder_mod->displayorder = $displayorder;
                            $kindorder_mod->aid          = $id;
                            $kindorder_mod->classid      = $kindid;
                            $kindorder_mod->typeid       = $this->type_id;
                        }
                        $kindorder_mod->save();
                        if ($kindorder->saved())
                            echo 'ok';
                        else
                            echo 'no';

                    }
                } else if (strpos($id, 'suit') !== FALSE) {
                    $suitid    = substr($id, strpos($id, '_') + 1);
                    $value_arr = array('displayorder' => $displayorder);
                    $updated   = DB::update('ferry_ticket')->set($value_arr)->where('id', '=', $suitid)->execute();
                    if ($updated)
                        echo 'ok';
                    else
                        echo 'no';
                }
            } else {
                //如果不是排序字段
                if (is_numeric($id)) {
                    $model = ORM::factory('ferry', $id);
                } else if (strpos($id, 'suit') !== FALSE) {
                    $suitid = substr($id, strpos($id, '_') + 1);
                    $model  = ORM::factory('ferry_ticket', $suitid);
                }
                if ($model->id) {
                    $model->$field = $val;
                    if ($field == 'kindlist') {
                        $model->$field = implode(',', Model_Destinations::getParentsStr($val));
                    } else if ($field == 'attrid') {
                        $model->$field = implode(',', Model_Attrlist::getParentsStr($val, $this->type_id));
                    }
                    $model->save();
                    if ($model->saved())
                        echo 'ok';
                    else
                        echo 'no';
                }
            }
        }
    }

    // 添加景点
    public function action_add()
    {
        $this->assign('webid', 0);
        $this->assign('position', '添加景点');
        $this->assign('action', 'add');
        $columns = ORM::factory('ferry_content')->where("(webid=0 and isopen=1) and columnname!='tupian'")->order_by('displayorder', 'asc')->get_all();
        $extended_data = Model_Ferry_Extend_Field::get_data();

        $this->assign('extended_data', $extended_data);
        $this->assign('columns', $columns);
        $this->display('admin/ferry/edit');
    }

    // 修改景点
    public function action_edit()
    {
        $productid = $this->params['id'];

        $info                     = ORM::factory('ferry', $productid)->as_array();
        $info['kindlist_arr']     = ORM::factory('destinations')->getKindlistArr($info['kindlist']);//目的地数组
        $info['attrlist_arr']     = json_encode(Common::getSelectedAttr($this->type_id, $info['attrid']));//属性数组
        $info['iconlist_arr']     = Common::getSelectedIcon($info['iconlist']);//json_encode(Common::getSelectedIcon($info['iconlist']));//图标数组
        $info['supplier_arr']     = ORM::factory('supplier', $info['supplierlist'])->as_array();
        $info['piclist_arr']      = json_encode(Common::getUploadPicture($info['piclist']));//图片数组
        $info['jifenbook_info']   = DB::select()->from('jifen')->where('id', '=', $info['jifenbook_id'])->execute()->current();
        $info['jifentprice_info'] = DB::select()->from('jifen_price')->where('id', '=', $info['jifentprice_id'])->execute()->current();

        // 门票
        $tickets = DB::select()->from('ferry_ticket')
            ->where('ferryid', '=', $productid)
            ->and_where('status','!=',0)
            ->order_by('id', 'desc')
            ->execute()->as_array();

        // 全部场次
        $all_period_time = DB::select()->from('ferry_period_time')->execute()->as_array();

        // 已关联的场次
        $period_times = DB::select()
            ->from('ferry_ticket_period_time')
            ->where('ferry_id', '=', $productid)
            ->execute()
            ->as_array('id', 'period_time_id');

        // 人群配置
        $people_group_config = Model_Ferry_People_Config::get_ferry_edit_config($productid);

        // 价格规格
        $skus = Model_Ferry_Ticket_Sku::get_price_sku($productid);

        $columns    = ORM::factory('ferry_content')
            ->where("(webid=0 and isopen=1) and columnname!='tupian'")
            ->order_by('displayorder', 'asc')
            ->get_all();
        $extendinfo = Common::getExtendInfo($this->type_id, $info['id']);

        // uniapp端图片
        $uni_images = Model_Uniapp_Images::get_product_img($this->type_id, $info['id']);

        $extended_data = Model_Ferry_Extend_Field::get_data($info['id']);

        $this->assign('extended_data', $extended_data);
        $this->assign('uni_images', $uni_images);
        $this->assign('action', 'edit');
        $this->assign('people_group_config', $people_group_config);
        $this->assign('tickets', $tickets);
        $this->assign('skus', $skus);
        $this->assign('all_period_time', $all_period_time);
        $this->assign('period_times', $period_times);
        $this->assign('columns', $columns);
        $this->assign('extendinfo', $extendinfo);//扩展信息
        $this->assign('info', $info);
        $this->assign('position', '修改景点' . $info['title']);
        $this->display('admin/ferry/edit');
    }

    // 保存景点(ajax)
    public function action_ajax_save()
    {
        $action = Arr::get($_POST, 'action');//当前操作
        $id     = Arr::get($_POST, 'productid');

        $status   = false;
        $webid    = Arr::get($_POST, 'webid');//所属站点
        $kindlist = Arr::get($_POST, 'kindlist');
        if ($webid != 0)//自动添加子站目的地属性
        {
            if (is_array($kindlist)) {
                if (!in_array($webid, $kindlist)) {
                    array_push($kindlist, $webid);
                }
            } else {
                $kindlist = array($webid);//如果为空则直接加webid
            }
        }

        //添加操作
        if ($action == 'add' && empty($id)) {
            $model          = ORM::factory('ferry');
            $model->aid     = Common::getLastAid('sline_ferry', $webid);
            $model->addtime = time();
        } else {
            $model = ORM::factory('ferry', $id);
            if ($model->webid != $webid) //如果更改了webid重新生成aid
            {
                $aid        = Common::getLastAid('sline_ferry', $webid);
                $model->aid = $aid;
            }
        }

        //选中上级属性
        $attrids = implode(',', Arr::get($_POST, 'attrlist'));//属性
        if (!empty($attrids)) {
            $attrmode = ORM::factory("ferry_attr")->where("id in ($attrids)")->group_by('pid')->get_all();
            foreach ($attrmode as $k => $v) {
                $attrids = $v['pid'] . ',' . $attrids;
            }
        }

        $imagestitle  = Arr::get($_POST, 'imagestitle');
        $images       = Arr::get($_POST, 'images');
        $imgheadindex = Arr::get($_POST, 'imgheadindex');

        //图片处理
        $piclist = '';
        $litpic  = $images[$imgheadindex];
        foreach ($images as $key => $value) {
            $desc    = isset($imagestitle[$key]) ? $imagestitle[$key] : '';
            $pic     = !empty($desc) ? $images[$key] . '||' . $desc : $images[$key];
            $piclist .= $pic . ',';
        }
        $piclist          = strlen($piclist) > 0 ? substr($piclist, 0, strlen($piclist) - 1) : '';//图片
        $model->title     = Arr::get($_POST, 'title');
        $model->shortname = Arr::get($_POST, 'shortname');
        $model->address   = Arr::get($_POST, 'address');
        $model->webid     = $webid;

        $model->shownum       = Arr::get($_POST, 'shownum') ? Arr::get($_POST, 'shownum') : 0;
        $model->author        = Arr::get($_POST, 'author');//编辑人
        $model->telephone     = Arr::get($_POST, 'telephone');//编辑人
        $model->ishidden      = Arr::get($_POST, 'ishidden') ? Arr::get($_POST, 'ishidden') : 0;//显示隐藏
        $model->getway        = Arr::get($_POST, 'getway');//取票方式
        $model->sellpoint     = Arr::get($_POST, 'sellpoint');
        $model->product_video = Arr::get($_POST, 'product_video');
        $model->attrid        = $attrids;//属性
        $model->lng           = Arr::get($_POST, 'lng') ? Arr::get($_POST, 'lng') : 0;
        $model->lat           = Arr::get($_POST, 'lat') ? Arr::get($_POST, 'lat') : 0;

        $model->iconlist     = implode(',', Arr::get($_POST, 'iconlist'));//图标
        $model->satisfyscore = Arr::get($_POST, 'satisfyscore') ? Arr::get($_POST, 'satisfyscore') : 0;//满意度
        $model->bookcount    = Arr::get($_POST, 'bookcount') ? Arr::get($_POST, 'bookcount') : 0;//销量
        $model->piclist      = $piclist;
        $link                = new Model_Tool_Link();
        $model->content      = $link->keywordReplaceBody(Arr::get($_POST, 'content'), $this->type_id);
        $model->isferryarea   = 0;
        $model->booknotice   = Arr::get($_POST, 'booknotice');
        $model->recommendnum = $_POST['recommendnum'];
        $model->seotitle     = Arr::get($_POST, 'seotitle');//优化标题
        $model->tagword      = Arr::get($_POST, 'tagword');
        if (St_Functions::is_normal_app_install('mobiledistribution')) {
            $model->fenxiao_status = Model_Fenxiao_Config::get_val('cfg_main_fenxiao_status');;
        }
        $model->keyword        = Arr::get($_POST, 'keyword');
        $model->description    = Arr::get($_POST, 'description');
        $model->kindlist       = implode(',', Model_Destinations::getParentsStr(implode(',', $kindlist)));//所属目的地
        $model->finaldestid    = empty($_POST['finaldestid']) ? Model_Destinations::getFinaldestId(explode(',', $model->kindlist)) : $_POST['finaldestid'];
        $model->attrid         = implode(',', Arr::get($_POST, 'attrlist'));//属性
        $model->iconlist       = implode(',', Arr::get($_POST, 'iconlist'));//图标
        $model->supplierlist   = implode(',', Arr::get($_POST, 'supplierlist'));
        $model->modtime        = time();
        $model->jifenbook_id   = empty($_POST['jifenbook_id']) ? 0 : $_POST['jifenbook_id'];
        $model->jifentprice_id = empty($_POST['jifentprice_id']) ? 0 : $_POST['jifentprice_id'];
        $model->open_time_des  = $_POST['open_time_des'];
        $model->templet        = $_POST['templet'];
        $model->wap_templet    = $_POST['wap_templet'];
        $model->litpic         = $litpic;

        // 保存人群信息
        $model->is_dist_people = Arr::get($_POST, 'is_dist_people', 0);

        // 保存多套餐预订
        $model->is_open_multiple_ticket     = Arr::get($_POST, 'is_open_multiple_ticket', 0);
        $model->multiple_rule_ticket_id = Arr::get($_POST, 'multiple_rule_ticket_id', '');

        if ($action == 'add' && empty($id)) {
            $model->create();
        } else {
            $model->update();
        }

        if ($model->saved()) {
            if ($action == 'add') {
                $product_id = $model->id; //插入的产品id
            } else {
                $product_id = $model->id;
            }
            Common::saveExtendData($this->type_id, $product_id, $_POST);//扩展信息保存
            $status = true;

            // 保存人群信息
            Model_Ferry_People_Config::save_ferry_people_config($product_id, $_POST);

            // 如果开启多套餐关闭分时预约
            if( $model->is_open_multiple_ticket  == 1) {
                Model_Ferry_Ticket_Sku::close_period_time($product_id);
            }

            // 保存uniapp图片
            $uni_images  = Arr::get($_POST, 'uni_images');
            $uni_img_key = Arr::get($_POST, 'uni_img_key');
            Model_Uniapp_Images::save_product_img(Model_Ferry::$typeid, $product_id, $uni_images, $uni_img_key);
        }

        echo json_encode(array('status' => $status, 'productid' => $product_id));
    }

    // 门票价格范围操作
    public function action_price()
    {
        $action = $this->params['action'];
        $this->assign('chooseid', 'attr_price');
        if (empty($action)) {
            $list = ORM::factory('ferry_pricelist')->where('webid', '=', '0')->order_by('min', 'asc')->get_all();
            $this->assign('list', $list);
            $this->display('admin/ferry/price');
        }
    }

    // 门票价格ajax操作
    public function action_ajax_price()
    {
        $action = $this->params['action'];
        //动态保存
        if ($action == 'save') {
            $max    = Arr::get($_POST, 'max');
            $min    = Arr::get($_POST, 'min');
            $id     = Arr::get($_POST, 'id');
            $newmin = Arr::get($_POST, 'newmin');
            $newmax = Arr::get($_POST, 'newmax');


            //保存原来的
            for ($i = 0; isset($id[$i]); $i++) {
                $obj = ORM::factory('ferry_pricelist')->where('id', '=', $id[$i])->find();
                if (!empty($min[$i])) $obj->min = $min[$i];
                if (!empty($max[$i])) $obj->max = $max[$i];
                $obj->update();
                $obj->clear();
            }
            //添加新的
            for ($i = 0; isset($newmin[$i]); $i++) {
                $obj = ORM::factory('ferry_pricelist');
                if (!empty($newmin[$i])) $obj->min = $newmin[$i];
                if (!empty($newmax[$i])) $obj->max = $newmax[$i];
                $obj->webid = 0;
                $obj->create();
                $obj->clear();
            }
            echo json_encode(array('status' => true));
        }
        //动态删除
        if ($action == 'del') {
            $id    = Arr::get($_POST, 'id');
            $model = ORM::factory('ferry_pricelist', $id);
            $model->delete();
            $out = array();
            if (!$model->loaded()) {
                $out['status'] = true;
            } else {
                $out['status'] = false;
            }
            echo json_encode($out);
        }
    }


    // 门票列表管理
    public function action_ticket()
    {

        $action = $this->params['action'];
        $ferryid = $this->params['ferryid'];
        $this->assign('ferryid', $ferryid);
        $this->assign('tickettypelist', json_encode(ORM::factory('ferry_ticket_type')->where('ferryid', '=', $ferryid)->order_by('displayorder', 'asc')->get_all()));
        if (empty($action)) {
            //显示列表页
            $info     = ORM::factory('ferry', $ferryid)->as_array();
            $position = $info['title'];
            $this->assign('position', $position);
            $this->display('admin/ferry/ticket_list');
        } else if ($action == 'read') {
            //读取列表
            $start          = Arr::get($_GET, 'start');
            $limit          = Arr::get($_GET, 'limit');
            $sql            = "select a.* from sline_ferry_ticket a where a.ferryid='$ferryid' order by a.displayorder asc limit $start,$limit";
            $totalcount_arr = DB::query(Database::SELECT, "select count(*) as num from sline_ferry_ticket a where ferryid='$ferryid'")->execute()->as_array();
            $list           = DB::query(Database::SELECT, $sql)->execute()->as_array();
            $new_list       = array();
            foreach ($list as $k => $v) {
                $new_list[] = $v;
            }
            $result['total']   = $totalcount_arr[0]['num'];
            $result['lists']   = $new_list;
            $result['success'] = true;

            echo json_encode($result);
        } else if ($action == 'save') {
            //保存字段
            $rawdata = file_get_contents('php://input');
            $field   = Arr::get($_GET, 'field');
            $data    = json_decode($rawdata);
            $id      = $data->id;
            if ($field) {
                $value_arr         = array();
                $value_arr[$field] = $data->$field;
                $updated           = DB::update('ferry_ticket')->set($value_arr)->where('id', '=', $id)->execute();
                if ($updated)
                    echo 'ok';
                else
                    echo 'no';
            }
        } else if ($action == 'delete') {
            //删除某个记录
            $rawdata = file_get_contents('php://input');
            $data    = json_decode($rawdata);
            $id      = $data->id;
            if (is_numeric($id)) {
                $model = ORM::factory('ferry_ticket', $id);
                $model->delete();

            }
        } else if ($action == 'update') {
            //更新单个字段.
            $id    = Arr::get($_POST, 'id');
            $field = Arr::get($_POST, 'field');
            $val   = Arr::get($_POST, 'val');
            $model = ORM::factory('ferry_ticket', $id);
            if ($model->id) {
                $model->$field = $val;
                $model->save();
                if ($model->saved())
                    echo 'ok';
                else
                    echo 'no';
            }
        }
    }



    // 门票类型管理
    public function action_tickettype()
    {
        $action = $this->params['action'];
        if (empty($action)) {
            $ferryid = $this->params['ferryid'];
            $list   = ORM::factory('ferry_ticket_type')->where('ferryid', '=', $ferryid)->get_all();
            $this->assign('list', $list);
            $this->assign('ferryid', $ferryid);
            $this->display('admin/ferry/suittype');
        } else if ($action == 'save') {
            $ferryid           = Arr::get($_POST, 'ferryid');
            $kindname_arr     = Arr::get($_POST, 'kindname');
            $displayorder_arr = Arr::get($_POST, 'displayorder');
            foreach ($kindname_arr as $k => $v) {
                $model = ORM::factory('ferry_ticket_type', $k);
                if ($model->id) {
                    $model->kindname     = $v;
                    $model->ferryid       = $ferryid;
                    $model->displayorder = $displayorder_arr[$k] ? $displayorder_arr[$k] : 9999;
                    $model->save();
                }
            }
            echo 'ok';
        } else if ($action == 'del') {
            $id    = Arr::get($_POST, 'id');
            $model = ORM::factory('ferry_ticket_type', $id);
            $model->delete();
            echo 'ok';
        } else if ($action == 'add') {
            $ferryid        = $_POST['ferryid'];
            $model         = ORM::factory('ferry_ticket_type');
            $model->ferryid = $ferryid;
            $model->save();
            $model->reload();
            echo $model->id;
        }
    }


    // 短信通知
    public function action_sms()
    {
        $model_info = DB::select()->from('model')->where('id', '=', $this->type_id)->execute()->current();
        $pinyin     = $model_info['pinyin'];
        $arr        = DB::select()->from('sms_msg')->where('msgtype', 'like', $pinyin . '_%')->execute()->as_array();
        foreach ($arr as $row) {
            $key = substr($row['msgtype'], strlen($pinyin . '_'));
            $this->assign($key, $row['msg']);
            $this->assign($key . '_open', $row['isopen']);
        }

        $this->display('admin/ferry/sms');
    }

    // 短信保存
    public function action_ajax_save_sms_msg()
    {
        $model_info = DB::select()->from('model')->where('id', '=', $this->type_id)->execute()->current();
        $pinyin     = $model_info['pinyin'];
        for ($i = 1; $i <= 11; $i++) {
            $_open          = 'isopen' . $i;
            $_msg           = 'order_msg' . $i;
            $open           = $_POST[$_open];
            $msg            = $_POST[$_msg];
            if(isset($_POST[$_open])){
                $msgtype        = $pinyin . '_' . $_msg;
                $model          = ORM::factory('sms_msg')->where('msgtype', '=', $msgtype)->find();
                $model->msgtype = $msgtype;
                $model->msg     = $msg;
                $model->isopen  = $open;
                $model->save();
            }
        }
        echo json_encode(array('status' => true, 'msg' => '提交成功'));
    }

    // 邮件通知
    public function action_email()
    {
        $model_info = DB::select()->from('model')->where('id', '=', $this->type_id)->execute()->current();
        $pinyin     = $model_info['pinyin'];
        $arr        = DB::select()->from('email_msg')->where('msgtype', 'like', $pinyin . '_%')->execute()->as_array();
        foreach ($arr as $row) {
            $key = substr($row['msgtype'], strlen($pinyin . '_'));
            $this->assign($key, $row['msg']);
            $this->assign($key . '_open', $row['isopen']);
        }
        $this->display('admin/ferry/email');
    }

    // 邮件保存
    public function action_ajax_save_email_msg()
    {
        $model_info = DB::select()->from('model')->where('id', '=', $this->type_id)->execute()->current();
        $pinyin     = $model_info['pinyin'];
        for ($i = 1; $i <= 4; $i++) {
            $_open          = 'isopen' . $i;
            $_msg           = 'order_msg' . $i;
            $open           = $_POST[$_open];
            $msg            = $_POST[$_msg];
            $msgtype        = $pinyin . '_' . $_msg;
            $model          = ORM::factory('email_msg')->where('msgtype', '=', $msgtype)->find();
            $model->msgtype = $msgtype;
            $model->msg     = $msg;
            $model->isopen  = $open;
            $model->save();
        }
        echo json_encode(array('status' => true, 'msg' => '提交成功'));
    }

    // 内容介绍
    public function action_content()
    {
        $action = $this->params['action'];
        if (empty($action)) {
            $ferrycontent = ORM::factory('ferry_content')->where('webid=0 and columnname!="tupian"')->order_by('displayorder')->get_all();
            $this->assign('list', $ferrycontent);
            $this->display('admin/ferry/content');
        } else if ($action == 'save') {
            $displayorder    = Arr::get($_POST, 'displayorder');
            $chinesename     = Arr::get($_POST, 'chinesename');
            $isopen          = Arr::get($_POST, 'isopen');
            $newdisplayorder = Arr::get($_POST, 'newdisplayorder');
            $newchinesename  = Arr::get($_POST, 'newchinesename');
            $newisopen       = Arr::get($_POST, 'newisopen');
            foreach ($displayorder as $k => $v) {
                $model = ORM::factory('ferry_content', $k);
                if ($model->id) {
                    $open                = $isopen[$k] ? 1 : 0;
                    $model->chinesename  = $chinesename[$k];
                    $model->displayorder = $v;
                    $model->isopen       = $open;
                    $model->save();
                }
            }
            //更新扩展字段描述
            Model_Ferry_Content::update_extend_field_name();
            echo 'ok';
        }
    }

    // 添加内容项
    public function action_ajax_content_add()
    {
        $extend_table = 'sline_ferry_extend_field';

        $lastIndex = Common::getExtendContentIndex($extend_table);
        $fieldName = 'e_' . 'content_' . $lastIndex;
        $result    = Common::addField($extend_table, 'content_' . $lastIndex, 'mediumtext', 0, '自定义' . $lastIndex);
        if ($result) {
            $data = Model_Ferry_Content::add_content_field($fieldName, '自定义' . $lastIndex);
            Model_Extend_Field::add_extend_field($this->type_id, $fieldName, '自定义' . $lastIndex);
            echo json_encode(array('status' => true, 'msg' => '添加成功', 'data' => $data));
        } else {
            echo json_encode(array('status' => false, 'msg' => '添加失败'));
        }
    }

    // 删除内容项
    public function action_ajax_content_del()
    {
        $id         = $_POST['id'];
        $model      = ORM::factory('ferry_content', $id);
        $columnName = $model->columnname;
        $model->delete();
        DB::query(Database::DELETE, "alter table `sline_ferry_extend_field` drop column $columnName")->execute();
        $extendModel = ORM::factory('extend_field')->where('typeid', '=', $this->type_id)->and_where('fieldname', '=', $columnName)->find();
        $extendModel->delete();
        echo json_encode(array('status' => true));
    }

    // 供应商审核
    public function action_dialog_supplier_check()
    {
        $action = $_GET['action'];
        $suitid = $_GET['suitid'];
        if (!$action) {
            $this->assign('suitid', $suitid);
            $this->display('admin/ferry/dialog_supplier_check');
        }
        if ($action == 'save') {
            $data = array(
                'status' => $_GET['status'],
                'refuse_msg' => $_GET['refuse_msg'],
                'modtime' => time(),
            );
            DB::update('ferry_ticket')->set($data)->where('id', '=', $suitid)->execute();
            echo 'ok';
        }
    }

    //预订须知
    public function action_agreement()
    {
        $fields = array('cfg_ferry_order_agreement_open', 'cfg_ferry_order_agreement', 'cfg_ferry_order_agreement_selected');
        $config = Model_Sysconfig::get_configs(0, $fields);
        $this->assign('config', $config);
        $this->display('admin/ferry/agreement');
    }


    // 异步获取模板列表
    public function action_ajax_get_template_list()
    {
        $page  = $_POST['page'];
        $webid = $_POST['webid'];
        if ($webid) {
            $pclist = Model_Templet::get_templet_list_by_page('sub_site', $page, $webid);
        } else {
            $pclist = Model_Templet::get_templet_list_by_page('pc', $page, $webid);
        }
        $waplist = Model_Templet::get_templet_list_by_page('wap', $page, 0);
        echo json_encode(array('pclist' => array_reverse($pclist), 'waplist' => array_reverse($waplist)));
    }

    // 添加门票类型
    public function action_ajax_add_ticket_type()
    {
        $db = Database::instance();
        $db->begin();
        try {
            $validation = Validation::factory($_POST)
                ->rule('name', 'not_empty')
                ->rule('ferry_id', 'not_empty');
            if (!$validation->check()) {
                $error = $validation->errors();
                $keys  = array_keys($validation->errors());
                throw new Exception("error_{$keys[0]}_{$error[$keys[0]][0]}");
            }

            $name    = Common::remove_xss(Arr::get($_POST, 'name'));
            $ferry_id = Arr::get($_POST, 'ferry_id');

            $return = Model_Ferry_Ticket_Type::add_ticket_type($ferry_id, $name);
            if (!$return['status']) {
                throw new Exception($return['msg']);
            }
            $db->commit();
        } catch (Exception $e) {
            $return = array('status' => false, 'msg' => $e->getMessage());
            $db->rollback();
        }

        echo json_encode($return);
    }

    // 景区人群管理
    public function action_people_set()
    {
        $this->assign('chooseid', 'people_set');
        $this->display('admin/ferry/people_group');
    }

    // 景区人群操作
    public function action_ajax_people()
    {
        try {
            $action = $this->params['action'];
            if ($action == 'read') {
                // 读取列表
                $list   = ORM::factory('ferry_people_group')->get_all();
                $result = array(
                    'data' => $list,
                    'status' => true,
                    'msg' => '获取成功'
                );
            } else if ($action == 'add') {
                // 新增
                Model_Ferry_People_Group::add_people();
                $result = array(
                    'status' => true,
                    'msg' => '新增成功'
                );
            } else if ($action == 'del') {
                // 删除
                $validation = Validation::factory($_POST)
                    ->rule('id', 'not_empty');
                if (!$validation->check()) {
                    $error = $validation->errors();
                    $keys  = array_keys($validation->errors());
                    throw new Exception("error_{$keys[0]}_{$error[$keys[0]][0]}");
                } else {
                    $id = Arr::get($_POST, 'id');
                    Model_Ferry_People_Group::del($id);
                    $result = array(
                        'status' => true,
                        'msg' => '删除成功'
                    );
                }
            } else if ($action == 'update') {
                $validation = Validation::factory($_POST)
                    ->rule('id', 'not_empty')
                    ->rule('field', 'not_empty')
                    ->rule('field', 'in_array', array(':value', array('is_show', 'name')))
                    ->rule('value', 'not_empty');
                if (!$validation->check()) {
                    $error = $validation->errors();
                    $keys  = array_keys($validation->errors());
                    throw new Exception("error_{$keys[0]}_{$error[$keys[0]][0]}");
                } else {
                    $id    = Arr::get($_POST, 'id');
                    $field = Arr::get($_POST, 'field');
                    $value = Arr::get($_POST, 'value');
                    if ($field == 'is_show') {
                        $value = $value == 1 ? 1 : 0;
                    }
                    $data   = array(
                        $field => $value
                    );
                    $bool   = Model_Ferry_People_Group::update_people($id, $data);
                    $msg    = $bool ? '保存成功' : '保存失败';
                    $result = array(
                        'status' => $bool,
                        'msg' => $msg
                    );
                }
            } else {
                throw new Exception('不支持的操作');
            }
        } catch (Exception $e) {
            $result = array(
                'status' => false,
                'msg' => $e->getMessage()
            );
        }
        exit(json_encode($result));
    }

    // 预约时段管理
    public function action_period_time()
    {
        $this->assign('chooseid', 'period_time');
        $list = ORM::factory('ferry_period_time')->get_all();
        $config = Model_Sysconfig::get_configs(0, 'cfg_ferry_is_open_period');

        $this->assign('config', $config);
        $this->assign('list', $list);
        $this->display('admin/ferry/period_time');
    }

    // 保存预约时段
    public function action_ajax_save_period_time()
    {
        $dates          = Arr::get($_POST, 'date', array());
        $is_open_period = Arr::get($_POST, 'cfg_ferry_is_open_period', 0);
        try {
            // 保存config配置
            $is_open_period = $is_open_period == 1 ? $is_open_period : 0;
            $configs        = array('webid' => 0, 'cfg_ferry_is_open_period' => $is_open_period);
            $config_bool    = Model_Sysconfig::save_config($configs);
            if (!$config_bool) {
                throw new Exception('配置保存失败');
            }

            // 保存时段
            Model_Ferry_Period_Time::save_date($dates);

            $return = array('status' => true, 'msg' => '保存成功');
        } catch (Exception $e) {
            $return = array('status' => false, 'msg' => $e->getMessage());
        }
        echo json_encode($return);
    }

    // 添加套餐
    public function action_ajax_add_suit()
    {
        $db = Database::instance();
        $db->begin();
        try {
            $validation = Validation::factory($_POST)
                ->rule('suit_name', 'not_empty')
                ->rule('ferry_id', 'not_empty');
            if (!$validation->check()) {
                $error = $validation->errors();
                $keys  = array_keys($validation->errors());
                throw new Exception("error_{$keys[0]}_{$error[$keys[0]][0]}");
            }

            $suit_name = Common::remove_xss(Arr::get($_POST, 'suit_name'));
            $ferry_id   = Arr::get($_POST, 'ferry_id');

            // 添加套餐
            $return = Model_Ferry_Ticket::add_suit($ferry_id, $suit_name);
            if (!$return['status']) {
                throw new Exception($return['msg']);
            }

            $db->commit();
        } catch (Exception $e) {
            $return = array('status' => false, 'msg' => $e->getMessage());
            $db->rollback();
        }
        echo json_encode($return);
    }

    // 删除套餐
    public function action_ajax_del_suit()
    {
        $db = Database::instance();
        $db->begin();
        try {
            $validation = Validation::factory($_POST)
                ->rule('ticket_id', 'not_empty');
            if (!$validation->check()) {
                $error = $validation->errors();
                $keys  = array_keys($validation->errors());
                throw new Exception("error_{$keys[0]}_{$error[$keys[0]][0]}");
            }

            $ticket_id = Arr::get($_POST, 'ticket_id');

            // 添加套餐
            $return = Model_Ferry_Ticket::del_suit($ticket_id);
            if (!$return['status']) {
                throw new Exception($return['msg']);
            }

            $db->commit();
        } catch (Exception $e) {
            $return = array('status' => false, 'msg' => $e->getMessage());
            $db->rollback();
        }
        echo json_encode($return);
    }

    // 切换销售属性
    public function action_ajax_sku_close()
    {
        $db = Database::instance();
        $db->begin();
        try {
            $validation = Validation::factory($_POST)
                ->rule('sku_name', 'not_empty')
                ->rule('ferry_id', 'not_empty');
            if (!$validation->check()) {
                $error = $validation->errors();
                $keys  = array_keys($validation->errors());
                throw new Exception("error_{$keys[0]}_{$error[$keys[0]][0]}");
            }

            $ferry_id  = Arr::get($_POST, 'ferry_id');
            $sku_name = Arr::get($_POST, 'sku_name');

            if ($sku_name == 'period_time') {
                // 处理场次
                Model_Ferry_Ticket_Sku::close_period_time($ferry_id);
            } else {

            }
            $db->commit();
            $return = array('status' => true, 'msg' => '保存成功');
        } catch (Exception $e) {
            $return = array('status' => false, 'msg' => $e->getMessage());
            $db->rollback();
        }
        echo json_encode($return);
    }

    // 处理某一个销售属性中某个数据的开启关闭
    public function action_ajax_change_one_sku()
    {
        $db = Database::instance();
        $db->begin();
        try {
            $validation = Validation::factory($_POST)
                ->rule('sku_name', 'not_empty')
                ->rule('sku_item_id', 'not_empty')
                ->rule('is_checked', 'not_empty')
                ->rule('ferry_id', 'not_empty');
            if (!$validation->check()) {
                $error = $validation->errors();
                $keys  = array_keys($validation->errors());
                throw new Exception("error_{$keys[0]}_{$error[$keys[0]][0]}");
            }

            $ferry_id     = Arr::get($_POST, 'ferry_id');
            $sku_name    = Arr::get($_POST, 'sku_name');
            $sku_item_id = Arr::get($_POST, 'sku_item_id');
            $is_checked  = Arr::get($_POST, 'is_checked');

            if ($sku_name == 'period_time') {
                // 处理场次
                $result = Model_Ferry_Ticket_Sku::change_sku_period_time($ferry_id, $sku_item_id, $is_checked);
            } else {

            }
            $db->commit();
            $return = array('status' => true, 'msg' => '保存成功');
        } catch (Exception $e) {
            $return = array('status' => false, 'msg' => $e->getMessage());
            $db->rollback();
        }
        echo json_encode($return);
    }

    // 获取后台套餐列表筛选条件
    public function action_ajax_get_suit_filter()
    {
        try {
            $validation = Validation::factory($_POST)
                ->rule('ferry_id', 'not_empty');
            if (!$validation->check()) {
                $error = $validation->errors();
                $keys  = array_keys($validation->errors());
                throw new Exception("error_{$keys[0]}_{$error[$keys[0]][0]}");
            }

            $ferry_id = Arr::get($_POST, 'ferry_id');

            $data = Model_Ferry_Ticket::get_suit_filter($ferry_id);

            $return = array('status' => true, 'msg' => '保存成功', 'data' => $data);
        } catch (Exception $e) {
            $return = array('status' => false, 'msg' => $e->getMessage());
        }
        echo json_encode($return);
    }

    // 获取套餐列表
    public function action_ajax_get_suit_list()
    {
        try {
            $validation = Validation::factory($_POST)
                ->rule('ferry_id', 'not_empty');
            if (!$validation->check()) {
                $error = $validation->errors();
                $keys  = array_keys($validation->errors());
                throw new Exception("error_{$keys[0]}_{$error[$keys[0]][0]}");
            }

            $ferry_id         = Arr::get($_POST, 'ferry_id');
            $ticket_id       = Arr::get($_POST, 'ticket', array());
            $period_time_id  = Arr::get($_POST, 'period_time', array());
            $status          = Arr::get($_POST, 'status', array(1, 2, 3));
            $settlement_type = Arr::get($_POST, 'settlement_type', array());
            $ticket_type = Arr::get($_POST, 'ticket_type', array());

            $params = array(
                'ticket_id' => $ticket_id,
                'period_time_id' => $period_time_id,
                'settlement_type' => $settlement_type,
                'ticket_type'=>$ticket_type,
                'status' => $status,
            );

            $data = Model_Ferry_Ticket::get_suit_list($ferry_id, $params);

            $return = array('status' => true, 'msg' => '保存成功', 'data' => $data);
        } catch (Exception $e) {
            $return = array('status' => false, 'msg' => $e->getMessage());
        }

        echo json_encode($return);
    }

    // 保存门票状态
    public function action_ajax_save_ticket_status()
    {
        $db = Database::instance();
        $db->begin();
        try {
            $validation = Validation::factory($_POST)
                ->rule('status', 'not_empty')
                ->rule('ticket_id', 'not_empty');
            if (!$validation->check()) {
                $error = $validation->errors();
                $keys  = array_keys($validation->errors());
                throw new Exception("error_{$keys[0]}_{$error[$keys[0]][0]}");
            }

            $status    = Arr::get($_POST, 'status', 2);
            $ticket_id = Arr::get($_POST, 'ticket_id');
            if($status==999){
                $return = Model_Ferry_Ticket::delete_ticket($ticket_id);
            }else{
                $status    = $status == 3 ? $status : 2;
                $return = Model_Ferry_Ticket::save_ticket_status($status, $ticket_id);
            }
            $db->commit();
        } catch (Exception $e) {
            $db->rollback();
            $return = array('status' => false, 'msg' => $e->getMessage());
        }

        echo json_encode($return);
    }

    // 保存门票结算方式
    public function action_ajax_save_settlement_type()
    {
        try {
            $validation = Validation::factory($_POST)
                ->rule('settlement_type', 'not_empty')
                ->rule('ticket_id', 'not_empty');
            if (!$validation->check()) {
                $error = $validation->errors();
                $keys  = array_keys($validation->errors());
                throw new Exception("error_{$keys[0]}_{$error[$keys[0]][0]}");
            }

            $settlement_type = Arr::get($_POST, 'settlement_type', 1);
            $ticket_id       = Arr::get($_POST, 'ticket_id');
            $settlement_type = $settlement_type == 1 ? $settlement_type : 2;

            $return = Model_Ferry_Ticket::save_ticket_settlement_type($settlement_type, $ticket_id);
        } catch (Exception $e) {
            $return = array('status' => false, 'msg' => $e->getMessage());
        }

        echo json_encode($return);
    }

    // 编辑门票
    public function action_dialog_edit_suit()
    {
        $id = $this->params['id'];
        if ($id) {
            $info = Model_Ferry_Ticket::get_edit_info($id);

            $refund_rule = Model_Ferry_Refund_Rule::get_instance()->get_refund_rule($id);

            $this->assign('refund_rule', $refund_rule);
            $this->assign('info', $info);
            $this->display('admin/ferry/suit/dialog_edit');
        }
    }

    // 保存门票信息
    public function action_ajax_save_ticket()
    {
        try {
            $validation = Validation::factory($_POST)
                ->rule('ticket_id', 'not_empty');
            if (!$validation->check()) {
                $error = $validation->errors();
                $keys  = array_keys($validation->errors());
                throw new Exception("error_{$keys[0]}_{$error[$keys[0]][0]}");
            }

            $result = Model_Ferry_Ticket::save_ticket($_POST);
        } catch (Exception $e) {
            $result = array('status' => false, 'msg' => $e->getMessage());
        }
        exit(json_encode($result));
    }

    // 获取价格日历
    public function action_ajax_get_price_calendar()
    {
        try {
            $validation = Validation::factory($_POST)
                ->rule('ferry_id', 'not_empty');
            if (!$validation->check()) {
                $error = $validation->errors();
                $keys  = array_keys($validation->errors());
                throw new Exception("error_{$keys[0]}_{$error[$keys[0]][0]}");
            }

            $ferry_id = Arr::get($_POST, 'ferry_id');

            $tickets = Model_Ferry_Ticket_Price::get_ferry_price_calendar($ferry_id, $_POST);

            $result = array('status' => true, 'data' => array('suit' => $tickets));
        } catch (Exception $e) {
            $result = array('status' => false, 'msg' => $e->getMessage());
        }
        exit(json_encode($result));
    }

    // 获取景点门票规格
    public function action_ajax_get_price_suit_sku()
    {
        try {
            $validation = Validation::factory($_POST)
                ->rule('ferry_id', 'not_empty');
            if (!$validation->check()) {
                $error = $validation->errors();
                $keys  = array_keys($validation->errors());
                throw new Exception("error_{$keys[0]}_{$error[$keys[0]][0]}");
            }

            $ferry_id = Arr::get($_POST, 'ferry_id');

            $skus = Model_Ferry_Ticket_Sku::get_price_sku($ferry_id);

            $result = array('status' => true, 'data' => $skus);
        } catch (Exception $e) {
            $result = array('status' => false, 'msg' => $e->getMessage());
        }
        exit(json_encode($result));
    }

    // 编辑价格（单个|批量）
    public function action_dialog_edit_price()
    {
        try {
            $validation = Validation::factory($_GET)
                ->rule('ferry_id', 'not_empty');
            if (!$validation->check()) {
                $error = $validation->errors();
                $keys  = array_keys($validation->errors());
                throw new Exception("error_{$keys[0]}_{$error[$keys[0]][0]}");
            }

            $action  = $this->params['action'];
            $ferry_id = Arr::get($_GET, 'ferry_id');

            $this->assign('ferry_id', $ferry_id);
            if ($action == 'all') {
                // 价格规格
                $skus                 = Model_Ferry_Ticket_Sku::get_price_sku($ferry_id);
                $skus_settlement_list = [
                    'profit_type'     => [],
                    'commission_type' => [],
                ];
                foreach ($skus as $v) {
                    if ($v['settlement_type'] == 1) {
                        $skus_settlement_list['profit_type'][] = $v;
                    }else{
                        $skus_settlement_list['commission_type'][] = $v;
                    }
                }
                // 检查结算模式
                $settlement_type_arr    = Arr::pluck($skus, 'settlement_type');
                $settlement_type_arr    = array_unique($settlement_type_arr);
                $settlement_type_single = !(count($settlement_type_arr) > 1); // 是否是单个结算类型
                $settlement_type        = $settlement_type_single ? $settlement_type_arr[0] : '';

                $this->assign('skus_settlement_list', $skus_settlement_list);
                $this->assign('settlement_type_single', $settlement_type_single);
                $this->assign('settlement_type', $settlement_type);
                $this->assign('skus', $skus);
                $this->display('admin/ferry/suit/dialog_edit_all_price');
            } else {
                $ticket_id = Arr::get($_GET, 'ticket_id');
                $sku_id    = Arr::get($_GET, 'sku_id');
                $date      = Arr::get($_GET, 'date');
                $params    = array(
                    'ticket_id' => $ticket_id,
                    'sku_id'    => array(
                        $ticket_id => array($sku_id)
                    )
                );
                $skus      = Model_Ferry_Ticket_Sku::get_price_sku($ferry_id, $params);
                if (empty($skus)) {
                    throw new Exception('报价套餐不存在');
                }
                $price_params = array(
                    'ticket_id' => $ticket_id,
                    'sku_id'    => $sku_id,
                    'date'      => $date,
                );
                $price        = Model_Ferry_Ticket_Price::get_price($price_params);
                $settlement_type = Model_Ferry_Ticket::get_settlement_type($ticket_id);

                $this->assign('settlement_type', $settlement_type);
                $this->assign('ferry_id', $ferry_id);
                $this->assign('date', $date);
                $this->assign('price', $price);
                $this->assign('sku', $skus[0]);
                $this->display('admin/ferry/suit/dialog_edit_price');
            }
        } catch (Exception $e) {
            exit($e->getMessage());
        }
    }

    // 保存价格库存
    public function action_ajax_save_batch_price()
    {
        try {
            $validation = Validation::factory($_POST)
                ->rule('ferry_id', 'not_empty');
            if (!$validation->check()) {
                $error = $validation->errors();
                $keys  = array_keys($validation->errors());
                throw new Exception("error_{$keys[0]}_{$error[$keys[0]][0]}");
            }

            $ferry_id = Arr::get($_POST, 'ferry_id');

            Model_Ferry_Ticket_Price::save_batch_price($ferry_id, $_POST);
            Model_Ferry_Ticket_Price::save_settlement_data($_POST);

            $result = array('status' => true, 'msg' => '保存成功');
        } catch (Exception $e) {
            $result = array('status' => false, 'msg' => $e->getMessage());
        }
        exit(json_encode($result));
    }

    // 保存单个价格
    public function action_ajax_save_price()
    {
        try {
            $validation = Validation::factory($_POST)
                ->rule('ferry_id', 'not_empty')
                ->rule('sku_id', 'not_empty')
                ->rule('ticket_id', 'not_empty')
                ->rule('day', 'not_empty')
                ->rule('stock_mod', 'not_empty');
            if (!$validation->check()) {
                $error = $validation->errors();
                $keys  = array_keys($validation->errors());
                throw new Exception("error_{$keys[0]}_{$error[$keys[0]][0]}");
            }

            $ferry_id   = Arr::get($_POST, 'ferry_id');
            $ticket_id = Arr::get($_POST, 'ticket_id');
            $ticket    = DB::select('id', 'title', 'settlement_type')
                ->from('ferry_ticket')
                ->where('ferryid', '=', $ferry_id)
                ->and_where('id', '=', $ticket_id)
                ->execute()
                ->current();

            if ($ticket['settlement_type'] == 2) {
                $validation->rule('basic_price', 'not_empty');
            } else {
                $validation->rule('basic_price', 'not_empty')
                    ->rule('profit', 'not_empty');
            }
            if (!$validation->check()) {
                $error = $validation->errors();
                $keys  = array_keys($validation->errors());
                throw new Exception("error_{$keys[0]}_{$error[$keys[0]][0]}");
            }

            $sku_id = Arr::get($_POST, 'sku_id');
            $day    = Arr::get($_POST, 'day');
            $day    = strtotime($day);
            $sku    = array('ticket_id' => $ticket_id, 'sku_id' => $sku_id);

            Model_Ferry_Ticket_Price::save_one_price($ferry_id, $sku, $day, $_POST);
            Model_Ferry_Ticket_Price::save_settlement_data($_POST);

            $result = array('status' => true, 'msg' => '保存成功');
        } catch (Exception $e) {
            $result = array('status' => false, 'msg' => $e->getMessage());
        }
        exit(json_encode($result));
    }

    // 清除报价
    public function action_ajax_clear_price()
    {
        try {
            $validation = Validation::factory($_POST)
                ->rule('ferry_id', 'not_empty');
            if (!$validation->check()) {
                $error = $validation->errors();
                $keys  = array_keys($validation->errors());
                throw new Exception("error_{$keys[0]}_{$error[$keys[0]][0]}");
            }

            $ferry_id = Arr::get($_POST, 'ferry_id');
            $sku_id  = Arr::get($_POST, 'sku_id', '');

            Model_Ferry_Ticket_Price::clear_price($ferry_id, $sku_id);

            $result = array('status' => true, 'msg' => '保存成功');
        } catch (Exception $e) {
            $result = array('status' => false, 'msg' => $e->getMessage());
        }
        exit(json_encode($result));
    }

    // 清除单天报价
    public function action_ajax_clear_day_price()
    {
        try {
            $validation = Validation::factory($_POST)
                ->rule('ticket_id', 'not_empty')
                ->rule('sku_id', 'not_empty')
                ->rule('day', 'not_empty');
            if (!$validation->check()) {
                $error = $validation->errors();
                $keys  = array_keys($validation->errors());
                throw new Exception("error_{$keys[0]}_{$error[$keys[0]][0]}");
            }

            $ticket_id = Arr::get($_POST, 'ticket_id', '');
            $sku_id    = Arr::get($_POST, 'sku_id', '');
            $day       = Arr::get($_POST, 'day', '');

            $params = array(
                'ticket_id' => $ticket_id,
                'sku_id' => $sku_id,
                'day' => $day
            );

            Model_Ferry_Ticket_Price::del($params);
            $result = array('status' => true, 'msg' => '保存成功');
        } catch (Exception $e) {
            $result = array('status' => false, 'msg' => $e->getMessage());
        }
        exit(json_encode($result));
    }

    //价格库存上下架
    public function action_ajax_change_price_status()
    {
        try {
            $validation = Validation::factory($_POST)
                ->rule('ticket_id', 'not_empty')
                ->rule('status', 'not_empty')
                ->rule('status', 'in_array', array(':value', array(1, 0)));
            if (!$validation->check()) {
                $error = $validation->errors();
                $keys  = array_keys($validation->errors());
                throw new Exception("error_{$keys[0]}_{$error[$keys[0]][0]}");
            }

            $ticket_id = Arr::get($_POST, 'ticket_id');
            $status    = Arr::get($_POST, 'status', 1);
            $sku_id    = Arr::get($_POST, 'sku_id', '');
            $day       = Arr::get($_POST, 'day', '');

            $params = array(
                'sku_id' => $sku_id,
                'day' => $day,
            );

            Model_Ferry_Ticket_Price::change_price_status($ticket_id, $status, $params);

            $result = array('status' => true, 'msg' => '保存成功');
        } catch (Exception $e) {
            $result = array('status' => false, 'msg' => $e->getMessage());
        }
        exit(json_encode($result));
    }

    // 审核门票
    public function action_ajax_audit_ticket() {
        try {
            $validation = Validation::factory($_POST)
                ->rule('ticket_id', 'not_empty')
                ->rule('status', 'not_empty')
                ->rule('status', 'in_array', array(':value', array(3, 4)));
            if (!$validation->check()) {
                $error = $validation->errors();
                $keys  = array_keys($validation->errors());
                throw new Exception("error_{$keys[0]}_{$error[$keys[0]][0]}");
            }

            $ticket_id = Arr::get($_POST, 'ticket_id');
            $status    = Arr::get($_POST, 'status', 1);
            $refuse_msg    = Arr::get($_POST, 'refuse_msg', '');

            if ($status == 4) {
                $validation->rule('refuse_msg', 'not_empty');
            }

            $bool = Model_Ferry_Ticket::audit_ticket($ticket_id, $status, $refuse_msg);
            if(!$bool) {
                throw new Exception('保存失败');
            }
            $result = array('status' => true, 'msg' => '保存成功');
        } catch (Exception $e) {
            $result = array('status' => false, 'msg' => $e->getMessage());
        }
        exit(json_encode($result));
    }

    public function action_ajax_clone_ticket()
    {
        try {
            $ticket_id = Arr::get($_POST, 'ticket_id');
            $number    = Arr::get($_POST, 'number', 1);

            $ticket = DB::select()->from('ferry_ticket')->where('id', '=', $ticket_id)->execute()->current();
            unset($ticket['id']);

            $ticket['addtime']   = time();
            $ticket['modtime']   = time();
            $ticket['status']    = 2;
            $ticket['is_edited'] = 0;

            for ($i = 0; $i < $number; $i++) {
                DB::insert('ferry_ticket', array_keys($ticket))->values(array_values($ticket))->execute();
            }

            $result = array(
                'status' => true,
                'msg'    => '克隆成功'
            );
        } catch (Exception $e) {
            $result = array(
                'status' => false,
                'msg'    => $e->getMessage()
            );
        }
        exit(json_encode($result));
    }

    public function action_dialog_ticket_type_manage()
    {
        $id = $this->params['id'];
        $ticket_type = DB::select()->from('ferry_ticket_type')->where('ferryid','=',$id)->execute()->as_array();

        $this->assign('id', $id);
        $this->assign('ticket_type', $ticket_type);
        $this->display('admin/ferry/suit/dialog_ticket_type_manage');
    }

    public function action_ajax_add_type()
    {
        $id = Arr::get($_POST, 'id');
        $data = [
            'kindname'     => '自定义',
            'ferryid'       => $id,
            'displayorder' => '9999',
        ];
        $res = DB::insert('ferry_ticket_type', array_keys($data))->values(array_values($data))->execute();
        $data['id'] = $res[0];
        echo json_encode([
            'status' => true,
            'data'   => $data
        ]);
    }

    public function action_ajax_delete_type()
    {
        try {
            $id = Arr::get($_POST, 'type_id');
            $is_exist = DB::select()->from('ferry_ticket')->where('tickettypeid','=',$id)->execute()->valid();
            if($is_exist){
                throw new Exception('当前门票类型已被使用，不可删除！');
            }
            DB::delete('ferry_ticket_type')->where('id', '=', $id)->execute();
            $res = [
                'status' => true,
            ];
        } catch (Exception $e) {
            $res = [
                'status' => false,
                'msg'    => $e->getMessage(),
            ];
        }
        echo json_encode($res);
    }

    public function action_ajax_update_type()
    {
        $id    = Arr::get($_POST, 'type_id');
        $value = Arr::get($_POST, 'value');

        DB::update('ferry_ticket_type')->set([
            'kindname' => $value
        ])->where('id', '=', $id)->execute();
    }
}